package TrafficSim;

import java.util.Vector;

public class TrafficLightManager {
	
	private Vector <TrafficLightController> controllerList;
	private double startTime;
	private double switchTime = 20000;
	private double yellowTime = 500;
	private final int switchTimeCar = 1000;
	
	
	public TrafficLightManager (Vector <TrafficLightController> controllerList){
		
		this.controllerList = controllerList;
		startTime = System.currentTimeMillis();
	}

//	public void switchLights() {
//		
//		double timeDifference = System.currentTimeMillis() - startTime;
//		
//		if (timeDifference >= this.switchTime ){
//		
//			for (TrafficLightController controller : this.controllerList){
//				controller.switchState();
//				TrafficLight.State tls = controller.getTrafficLightState();
//				startTime = System.currentTimeMillis();
//				if (tls == TrafficLight.State.YELLOW || tls == TrafficLight.State.REDYELLOW){
//					startTime -= switchTime - yellowTime;
//				}
//				
//			}
//		}
//	}
	
	public void switchLights(int status) {

		switch(status){
		
		case 0:{
			double timeDifference = System.currentTimeMillis() - startTime;
			
			if (timeDifference >= this.switchTime ){
			
				for (TrafficLightController controller : this.controllerList){
					controller.switchStateStupid();
					TrafficLight.State tls = controller.getTrafficLightState();
					startTime = System.currentTimeMillis();
					if (tls == TrafficLight.State.YELLOW || tls == TrafficLight.State.REDYELLOW){
						startTime -= switchTime - yellowTime;
					}
					
				}
			}
			
			break;
		}
		
		case 1:{
			Vector<Street> streets;
			int counter = 0;
			Street street = null;
			Vector<Vehicle> v;
			for (TrafficLightController controller : this.controllerList){
				streets = controller.getIncomingStreets();
			
				
				for (Street s : streets){
					v = s.getVehicles();
					int counter2 = 0;
					for (Vehicle vehicle : v){
						if (vehicle.getDistanceToNextIntersection() < 100){
							counter2++;
						}
					}
					if (counter2 > counter){
						counter = counter2;
						street = s;
//						if (street == null){
//						return;
//						}
					}	
				}
				int switchtime = counter * this.switchTimeCar;
				double timeDifference = System.currentTimeMillis() + switchtime;
				if (street != null && street.getTrafficLight().getTlState() != TrafficLight.State.GREEN){
					controller.switchState(timeDifference, System.currentTimeMillis());
				}
			}
		}
			break;
		}
		
		}
		
		

}
